package helper;

import android.app.Activity;
import android.os.Bundle;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;

public abstract class FBHelper {
	public void ensureSessionOpenAndDoSomething(Activity activity) {
		Session session = Session.getActiveSession();
		
		if (session == null || !session.isOpened())
			Session.openActiveSession(activity, true, new SessionStatusCallback());
		else
			doAfterEnsureSessionOpen();
	}
	
	private class SessionStatusCallback implements Session.StatusCallback {

		@Override
		public void call(Session session, SessionState state, Exception exception) {
			if (session.isOpened())
				doAfterEnsureSessionOpen();
		}
	}
	
	protected abstract void doAfterEnsureSessionOpen();
	
	public void fqlQuery(String cols, String table, String where, String groupBy, String having,
			String orderBy, String limit) {
		String fqlQuery = "select " + cols;
		Bundle params = new Bundle();
		
		if (table != null)
			fqlQuery += " from " + table;
		if (where != null)
			fqlQuery += " where " + where;
		if (groupBy != null)
			fqlQuery += " group by " + groupBy;
		if (having != null)
			fqlQuery += " having " + having;
		if (orderBy != null)
			fqlQuery += " order by " + orderBy;
		if (limit != null)
			fqlQuery += " limit " + limit;
		params.putString("q", fqlQuery);
		Request request = new Request(Session.getActiveSession(), "/fql", params, HttpMethod.GET,
				new FqlQueryRequestCallback());
		Request.executeBatchAsync(request);
	}
	
	private class FqlQueryRequestCallback implements Request.Callback {

		@Override
		public void onCompleted(Response response) {
			doAfterFqlQuery(response);
		}
	}
	
	protected abstract void doAfterFqlQuery(Response response);
}
